<?php

/**
 * Created by PhpStorm.
 * User: 章利桂
 * Date: 2017/1/4
 * Time: 14:00
 */
class liveModel {
    const CANCEL_STATUS = -5;//已结束
    const PREPARE_START_STATUS = 0;//未开始
    const START_STATUS = 5;//进行中
    const OVER_STATUS = 10;//已结束
    const GOLD_RATE = 0.1;//元宝汇率（1:10）
    public function __construct(& $base)
    {
        $this->base = $base;
        $this->db = & $this->base->db;
        $this->redis = & $this->base->redis;
        $this->im = & $this->base->im;
        $this->erp =  isset($this->base->erp) ? $this->base->erp : $this->base->in_erpDb();
    }

    /**
     * 微课信息
     */
    public function getLiveInfo($liveId,$fields='*') {
        return  $this->db->getRow("select $fields from r_live_list where id=$liveId");
    }

    /**
     * 后台：查询直播列表
     */
    public function getList(array $params) {
//        $a = $this->im->chatroomQuery(8);
//        var_dump($a);
//        $b = $this->im->chatroomUserQuery(8,1,1);
//        var_dump($b);
        $start     = $params['start'] ? (int)$params['start'] : 0;
        $limitNum  = $params['limit'] ? (int)$params['limit'] : 10;
        $title     = isset($params['name']) ? trim($params['name']) : '';
        $status    = isset($params['status']) ? $params['status'] : -999;
        $where = '1=1';
        if ($title) {
            $where .=' and title like '."'%$title%'";
        }
        if ($status <> -999) {
            $where .=' and status ='.$status;
        }

        $sql ="select * from r_live_list where $where order by id desc limit $start,$limitNum";
        $cntsql ="select count(1) as cnt from r_live_list where $where";
        $this->total =  $this->db->getOne("$cntsql");
        $return =  $this->db->getAll($sql);
        return $return;
    }

    /**
     * 生成微课
     */
    public function addLive(array $params) {
        $id = (int)$params['id'];
        $title = $params['title'];
        $image = $params['image'];
        $startTime = $params['startTime'];
        $price = (double)$params['price'];
        $quesGoldNum = (int)$params['quesGoldNum'];
        $content = $params['content'];
        $speakerId = $params['speakerId'];
        $hostId = $params['hostId'];
        $limitNum = $params['limitNum'];
        $data = array(
            'title'=>$title,
            'image_url'=>$image,
            'speaker_id'=>$speakerId,
            'start_time'=>strtotime($startTime),
            'question_gold_num'=>$quesGoldNum,
            'content'=>$content,
            'price'=>$price,
            'limit_num'=>$limitNum
        );
        if (!$id) {
            $data['title'] = $title;
            $data['host_id'] = $hostId;
            $data['status'] = 0;
            $data['create_time'] = time();

            $result = $this->db->insertRow('r_live_list',$data,mysqldb::INSERT_COMMON);
            if ($result) {//生成聊天室
                $r1 = $this->addChatRoom($result,$title);
//                if ($r1) {//加入聊天室
//                    $this->addUserToChatRoom($result, array($speakerId, $hostId));
//                }
                $this->chatUserAdd($speakerId, $result);
                $this->chatUserAdd($hostId, $result);
                $num = $this->sumJoinNum($result);
                $this->db->update("update r_live_list set join_num=$num where id=$result");
            }
        } else {
            $setStr = common::arrayToString($data);
            $sql = "update r_live_list set $setStr where id= $id";
            $result = $this->db->update($sql);
        }
        return $result;
    }

    /**
     * 生成聊天室
     */
    public function addChatRoom($liveId, $title) {
        $result = $this->im->chatroomCreate(array($liveId=>$title));
        if ($result && $re = json_decode($result, true)){
           return $re['code'] == 200 ? true : false;
        }
        return false;
    }

    /**
     * 销毁聊天室
     */
    public function destroyChatRoom($liveId) {
        $result = $this->im->chatroomDestroy($liveId);
        if ($result && $re = json_decode($result, true)){
            return $re['code'] == 200 ? true : false;
        }
        return false;
    }

    /**
     * 用户加入聊天室白名单
     */
    public function userWhiteListAdd($liveId, array $userId) {
        $result = $this->im->userWhiteListAdd($liveId, $userId);
        if ($result && $re = json_decode($result, true)){
            return $re['code'] == 200 ? true : false;
        }
        return false;
    }

    /**
     * 用户禁言
     */
    public function userGagAdd($chatroomId, $userId, $minute) {
        $result = $this->im->chatroomUserGagAdd($chatroomId, $userId, $minute);
        if ($result && $re = json_decode($result, true)){
            return $re['code'] == 200 ? true : false;
        }
        return false;
    }

    /**
     * 用户解禁
     */
    public function userGagRollback($chatroomId, $userId) {
        $result = $this->im->chatroomUserGagRollback($chatroomId, $userId);
        if ($result && $re = json_decode($result, true)){
            return $re['code'] == 200 ? true : false;
        }
        return false;
    }

    /**
     * 取消微课
     *
     */
    public function delLive($liveId) {
        //查询是否开始
        $info = $this->getLiveInfo($liveId);
        if (!$info || $info['status']<> 0) return false;
        //查询是否产生报名费或付费提问
        $priceCnt = $this->db->getOne("select id from r_live_gold_list where live_id=$liveId and `type`=1 and balance_type=0");
        if ($priceCnt > 0) {
             return false;
        }
        $isOrder = $this->erp->getOne("select id from r_order where act_type=6 and act_id=$liveId and status in(2,4) and pay_status=20");
        if ($isOrder){
            return false;
        }
        $result = $this->saveLiveStatus(1, $liveId);//取消;
        if ($result) {//销毁聊天室
            $this->destroyChatRoom($result);
        }
        return $result;
    }



    /**
     * 用户消费汇总
     */
    public function getGoldCostList(array $params) {
        $start     = $params['start'] ? (int)$params['start'] : 0;
        $limitNum  = $params['limit'] ? (int)$params['limit'] : 10;
        $title     = isset($params['name']) ? trim($params['name']) : '';
        if ($title) {
            $arrTwoId = $this->db->getAll("select id from r_live_list where title like '%$title%'");
            if (!$arrTwoId) {
                $this->total = 0;
                return [];
            }
            $arrId = [];
            foreach ($arrTwoId as $key=>$val) {
                $arrId[] = $val['id'];
            }
            $strId = implode(',', $arrId);
            $where = "live_id in($strId)";
        }
        $sql ="select uid,live_id,ques_gold_num,gift_gold_num from r_live_gold_sum where $where ORDER BY  id desc limit $start,$limitNum";
        $cntsql ="select count(1) as cnt from r_live_gold_sum where $where";
        $this->total =  $this->db->getOne("$cntsql");
        $return =  $this->db->getAll($sql);
        return $return;
    }

    /**
     * 查询主播
     */
    public function getSpeakerInfo($uid, $fields='*') {
        return $this->db->getRow("select $fields from r_live_speaker where uid=$uid and status=0");
    }

    /**
     * 主播列表
     */
    public function getSpeakerList(array $params) {
        $start     = $params['start'] ? (int)$params['start'] : 0;
        $limitNum  = $params['limit'] ? (int)$params['limit'] : 10;
        $sql = "select * from r_live_speaker where status=0 order by id desc limit $start,$limitNum";
        $result  = $this->db->getAll($sql);
        $cntSql ="select count(1) from r_live_speaker where status=0";
        $this->total = $this->db->getOne($cntSql);
        return $result;
    }

    /**
     * 添加主播
     */
    public function addSpeaker(array $params) {
        $uid = $params['uid'];
        $status = $params['status'];
        $time = time();
        $data = array(
            'uid'=>$uid,
            'status'=>$status,
            'create_time'=>$time
        );
        $insertStr = common::arrayToString($data);
        $result = $this->db->insert("insert HIGH_PRIORITY into r_live_speaker set {$insertStr} on duplicate key update {$insertStr}");
        return $result;
    }

    /**
     * 移除主播
     */
    public function delSpeaker($speakerId) {
        $result = $this->db->update("update r_live_speaker set status=-1 where uid=$speakerId");
        if (!$result){
            return false;
        }
        return true;
    }

    /********************************************接口START****************************************/

    /**
     * 查询跑步有道-微课信息入口
     * 排序规则：进行中>预告中>已结束，无则不显示
     */
    public function getHomeLiveInfo($uid = 0) {
        $result = [];
        $statusArr = common::$liveStatus;
        $info = [];
        $list = $this->db->getAll('select * from r_live_list where status='.self::START_STATUS.' limit 3');
        if (!$list) {
            $list = $this->db->getAll('select * from r_live_list where status='.self::PREPARE_START_STATUS.' limit 3');
            if (!$list) {
                $list = $this->db->getAll('select * from r_live_list where status='.self::OVER_STATUS.' limit 3');
            }
        }
        if ($list) {
            $num  = count($list);
            if ($num == 1)  {
                $randNum = 0;
            } else {
                $randNum = rand(0,$num-1);
            }
            $info = $list[$randNum];
        }
        if (!$info) return $result;
        $header = $this->redis->hget(REDIS_PREFIX . 'UserInfo_' . $info['speaker_id'],'header');
        $nickname = $this->redis->hget(REDIS_PREFIX . 'UserInfo_' . $info['speaker_id'],'nickname');
        $result['id'] = $info['id'];
        $result['imageUrl'] = $info['image_url'];
        $result['title'] = $info['title'];
        $result['userInfo'] = array(
            'uid'=>$info['speaker_id'],
            'header'=>$header ? $header : "http://irun.hupu.com/static/bootstrap/img/jog_logo.png",
            'nickname'=>$nickname,
            'role'=>1
        );
        $result['status'] = $info['status'];
        $result['statusMsg'] = $statusArr[$info['status']];
        $result['joinNum'] = $info['join_num'];
        $result['msgNum'] = $info['msg_num'];//消息总数
        $result['isJoin'] = (int)$uid > 0 ? $this->getUserIsJoinLive($uid, $info['id']) : 0;
        return $result;

    }

    /**
     * 查询用户是否参与了微课
     */
    public function getUserIsJoinLive($uid, $liveId) {
        //$isOrder = $this->erp->getOne("select id from r_order where uid=$uid and act_type=6 and act_id=$liveId and status in(2,4) and pay_status=20");
        $isOrder = $this->db->getOne("select id from r_live_user where live_id=$liveId and uid=$uid");
        return  $isOrder ? 1 : 0;
    }

    /**
     * 查询用户是否付费报名成功了微课
     */
    public function getUserIsSignUpLive($uid, $liveId) {
        $isPay = $this->erp->getOne("select id from r_order where uid=$uid and act_type=6 and act_id=$liveId and status in(2,4) and pay_status=20");
        return  $isPay ? 1 : 0;
    }

    /**
     * 查询用户参与的微课ID
     * $param role '角色： 1 普通用户 2 主播 3 主持人'
     */
    public function getUserJoinLiveId($uid, $role=0) {
        $sql = "select DISTINCT live_id from r_live_user where uid=$uid and status=0";
        switch($role) {
            case 1:
                $sql .= " and role=0";
                break;
            case 2:
                $sql .= " and role=1";
                break;
            case 3:
                $sql .= " and role=2";
                break;
        }
        $arrActId = $this->db->getAll($sql);
        if (!$arrActId) {
           return [];
        }
        $arrLiveId = [];
        foreach ($arrActId as $key=>$val) {
            $arrLiveId[] = $val['live_id'];
        }
       return $arrLiveId;
    }

    /**
     * 查询融云消息是否存在
     */
    public function getIsExistMsg($imId) {
        return $this->db->getOne("select id from r_live_chatroom_message where im_id='$imId'");
    }

    /**
     * 查看融云消息的微课ID
     */
    public function getLiveIdByImid($imId) {
        return $this->db->getOne("select live_id from r_live_chatroom_message where im_id='$imId'");
    }

    /**
     * 查询微课列表接口
     * 分页，20条/页
     * 排序规则：进行中>预告中>已结束，无则不显示
     */
    public function getLiveList(array $params) {
        $start     = $params['start'] ? (int)$params['start'] : 0;
        $limitNum  = $params['offset'] ? (int)$params['offset'] : 10;
        $uid = (int)$params['uid'] ? (int)$params['uid'] : 0;
        $countSql = "SELECT count(1) from (SELECT * from r_live_list where status=5 UNION SELECT * from r_live_list where status=0  UNION SELECT * from r_live_list where status=10) as a";
        $this->total = $this->db->getOne($countSql);
        if (!$this->total) {
           return [];
        }
        $sql ="SELECT * from (SELECT * from r_live_list where status=5 UNION SELECT * from r_live_list where status=0  UNION SELECT * from r_live_list where status=10) as a limit $start,$limitNum";
        $result = $this->db->getAll($sql);
        $list = [];
        $arrStatus = common::$liveStatus;
        foreach($result as $key=>$val) {
            $header = $this->redis->hget(REDIS_PREFIX . 'UserInfo_' . $val['speaker_id'],'header');
            $nickname = $this->redis->hget(REDIS_PREFIX . 'UserInfo_' . $val['speaker_id'],'nickname');
            $list[$key]['id'] = $val['id'];
            $list[$key]['title'] = $val['title'];
            $list[$key]['userInfo'] = array(
                'uid'=>$val['speaker_id'],
                'header'=>$header ? $header : "http://irun.hupu.com/static/bootstrap/img/jog_logo.png",
                'nickname'=>$nickname,
                'role'=>1
            );
            $list[$key]['status'] = $val['status'];
            $list[$key]['statusMsg'] = $arrStatus[$val['status']];
            $list[$key]['joinNum'] = $val['join_num'];
            $list[$key]['msgNum'] = $val['msg_num'];
            $list[$key]['imageUrl'] = $val['image_url'];
            $list[$key]['startTime'] = $val['start_time'];
            $list[$key]['timestamp'] = time();
            $list[$key]['isJoin'] = $uid ? $this->getUserIsJoinLive($uid, $val['id']) : 0;
        }
        return $list;
    }

    /**
     * 查询指定微课详情接口
     * （微课详情+聊天室ID+[商品ID+课程金额+是否已成功购买]+[元宝打赏配置]+Ta的微课+推荐微课）
     */
    public function getLiveDetailById(array $params) {
        $uid = (int)$params['uid'] ? (int)$params['uid'] : 0;
        $liveId = (int)$params['liveId'] ? (int)$params['liveId'] : 0;
        $detail = [];//当前微课详情
        $info = $this->getLiveInfo($liveId);
        if ($info) {
            $header = $this->redis->hget(REDIS_PREFIX . 'UserInfo_' . $info['speaker_id'],'header');
            $nickname = $this->redis->hget(REDIS_PREFIX . 'UserInfo_' . $info['speaker_id'],'nickname');
            $detail['id'] = $info['id'];
            $detail['title'] = $info['title'];
            $detail['imageUrl'] = $info['image_url'];
            $detail['status'] = $info['status'];
            $detail['startTime'] = $info['start_time'];
            $detail['price'] = $info['price'];
            $detail['content'] = $info['content'];
            $detail['userInfo'] = array(
                'uid'=>$info['speaker_id'],
                'header'=>$header ? $header : "http://irun.hupu.com/static/bootstrap/img/jog_logo.png",
                'nickname'=>$nickname,
                'role'=>1
            );
            $detail['joinNum'] = $info['join_num'];
            $detail['isJoin'] = $uid ? $this->getUserIsJoinLive($uid, $liveId) : 0;
            //参与人
            $joinPeople = [];
            if ($info['join_num'] > 0) {
                $arrJoinUid = $this->db->getAll("select uid from r_live_user where live_id=$liveId and role=0 order by id desc limit 3");
                if ($arrJoinUid) {
                   foreach ($arrJoinUid as $key=>$val) {
                       $headerJoin = $this->redis->hget(REDIS_PREFIX . 'UserInfo_' . $val['uid'],'header');
                       $joinPeople[] = array('uid'=>$val['uid'], 'header'=>$headerJoin ? $headerJoin : "http://irun.hupu.com/static/bootstrap/img/jog_logo.png");
                   }
                }
            }
            $detail['joinPeople'] = $joinPeople;
        }
        $otherLive = [];//他的其他微课
        $arrLiveId = $this->getUserJoinLiveId($info['speaker_id'], 2);
        $newArrLid = $arrLiveId;
        if ($arrLiveId && in_array($liveId, $arrLiveId)) {
            $keys = array_keys($arrLiveId, $liveId);
           unset($arrLiveId[$keys[0]]);
        }
        if (count($arrLiveId) > 0) {
            $strLiveId = implode(',', $arrLiveId);
            $list = $this->db->getAll("select id,title,image_url,start_time,speaker_id from r_live_list where id in($strLiveId) and status in(5,0,10) order by id desc  limit 5");
            if ($list) {
                foreach ($list as $key=>$val) {
                    $header = $this->redis->hget(REDIS_PREFIX . 'UserInfo_' . $val['speaker_id'],'header');
                    $nickname = $this->redis->hget(REDIS_PREFIX . 'UserInfo_' . $val['speaker_id'],'nickname');
                    $otherLive[$key]['id'] = $val['id'];
                    $otherLive[$key]['title'] = $val['title'];
                    $otherLive[$key]['imageUrl'] = $val['image_url'];
                    $otherLive[$key]['startTime'] = $val['start_time'];
                    $otherLive[$key]['userInfo'] = array(
                        'uid'=>$val['speaker_id'],
                        'header'=>$header ? $header : "http://irun.hupu.com/static/bootstrap/img/jog_logo.png",
                        'nickname'=>$nickname,
                        'role'=>1
                    );
                    $otherLive[$key]['isJoin'] = $this->getUserIsJoinLive($uid, $val['id']);
                }
            }
        }
        $moreLive = [];//更多微课
        if($newArrLid) {
            $strNewLid = implode(',', $newArrLid);
            $arrMore = $this->db->getAll("select id,title,image_url,start_time,speaker_id from r_live_list where id not in($strNewLid) and status in(0,5) order by id desc limit 5");
        } else {
            $arrMore = $this->db->getAll("select id,title,image_url,start_time,speaker_id from r_live_list where status in(5,0) order by id desc limit 5");
        }
        if ($arrMore) {
            foreach($arrMore as $key=>$val) {
                $header = $this->redis->hget(REDIS_PREFIX . 'UserInfo_' . $val['speaker_id'],'header');
                $nickname = $this->redis->hget(REDIS_PREFIX . 'UserInfo_' . $val['speaker_id'],'nickname');
                $moreLive[$key]['id'] = $val['id'];
                $moreLive[$key]['title'] = $val['title'];
                $moreLive[$key]['imageUrl'] = $val['image_url'];
                $moreLive[$key]['startTime'] = $val['start_time'];
                $moreLive[$key]['userInfo'] = array(
                    'uid'=>$val['speaker_id'],
                    'header'=>$header ? $header : "http://irun.hupu.com/static/bootstrap/img/jog_logo.png",
                    'nickname'=>$nickname,
                    'role'=>1
                );
                $moreLive[$key]['isJoin'] = $this->getUserIsJoinLive($uid, $val['id']);

            }
        }
        return array('detail'=>$detail, 'otherLive'=>$otherLive, 'moreLive'=>$moreLive);
    }

    /**
     * 查询聊天室内微课的相关信息
     */
    public function getLiveDetailForChatroom(array $params) {
        $liveId = (int)$params['liveId'] ? (int)$params['liveId'] : 0;
        $info = $this->getLiveInfo($liveId);
        $detail = [];
        if ($info) {
            $header = $this->redis->hget(REDIS_PREFIX . 'UserInfo_' . $info['speaker_id'],'header');
            $nickname = $this->redis->hget(REDIS_PREFIX . 'UserInfo_' . $info['speaker_id'],'nickname');
            $detail['id'] = $info['id'];
            $detail['title'] = $info['title'];
            $detail['imageUrl'] = $info['image_url'];
            $detail['status'] = $info['status'];
            $detail['startTime'] = $info['start_time'];
            $detail['content'] = $info['content'];
            $detail['quesGoldNum'] = $info['question_gold_num'];
            $detail['userInfo'] = array(
                'uid'=>$info['speaker_id'],
                'header'=>$header ? $header : "http://irun.hupu.com/static/bootstrap/img/jog_logo.png",
                'nickname'=>$nickname,
                'role'=>1
            );
            $detail['hostId'] = $info['host_id'];
            $detail['joinNum'] = $info['join_num'];
            $detail['quesNum'] = $this->getNoRelyQuesNum($liveId);
        }
        //礼物数量
        $giftArr = $this->getGiftAnalysis($liveId);
        sort($giftArr);
        return array($detail, $giftArr);
    }

    /**
     * 查询礼物数量
     */
    public function getGiftAnalysis($liveId) {
        //礼物数量
        $arrGift = $this->db->getAll("SELECT gift_type,count(1) as num FROM `r_live_gold_list` where live_id=$liveId and type=2 GROUP BY gift_type;");
        $giftArr = common::$giftList;
        $arrG = [];
        if ($arrGift) {
            foreach ($arrGift as $key=>$val) {
                $arrG[$val['gift_type']] = $val['num'];
            }
        }
        foreach ($giftArr as $key=>$val) {
            $giftArr[$key]['num'] = 0;
            if (isset($arrG[$val['id']])) {
                $giftArr[$key]['num'] = $arrG[$val['id']];
            }
        }

        return $giftArr;
    }

    /**
     * 查询 指定微课消息列表接口
     * （基本信息+消息列表+礼物列表，筛选+分页，50条/页，排序规则：时间正序）
     */
    public function getLiveMsgAllList(array $params) {
        $uid = $params['uid'];
        $liveId = (int)$params['liveId'] ? (int)$params['liveId'] : 0;
        $type = $params['type']== 1 ? (int)$params['type'] : 0;//0 全部消息 1 问答墙消息
        $mid = (int)$params['mid'] ? (int)$params['mid'] : 0;
        $limitNum  = $params['offset'] ? (int)$params['offset'] : 10;
        $direc = $params['direc'] =='next' ? 'next' : 'prev';//数据追加方式

        //消息数量
        $msgList = [];
        $where = "live_id=$liveId and status=0";
        if ($type == 1) {
            $where .=" and icon in(1,2)";
        }
        $sort = 0;//是否需要重新排序
        if ($mid>0) {
            if ($direc == 'next') {
                $where .=" and id >$mid";
                $order = 'create_time asc';
            } else {
                $sort = 1;
                $where .=" and id <$mid";
                $order = 'create_time desc';
            }
        } else {
            $sort = 1;
            $order = 'create_time desc';
        }


        $list = $this->db->getAll("select * from r_live_chatroom_message where $where order by $order limit $limitNum");
        $arrSort = [];
        if ($list) {
            foreach($list as $key=>$val){
                $header = $this->redis->hget(REDIS_PREFIX . 'UserInfo_' . $val['uid'],'header');
                $nickname = $this->redis->hget(REDIS_PREFIX . 'UserInfo_' . $val['uid'],'nickname');
                $arrMsgExt = $this->db->getRow("select content,msg_type,voice_sec from r_live_chatroom_message_ext where mid={$val['id']}");
                $msgList[$key]['id'] = $val['id'];
                $msgList[$key]['imId'] = $val['im_id'];
                $msgList[$key]['userInfo'] = array(
                    'uid'=>$val['uid'],
                    'header'=>$header ? $header : "http://irun.hupu.com/static/bootstrap/img/jog_logo.png",
                    'nickname'=>$nickname,
                    'role'=>$val['role']
                );
                $msgList[$key]['icon'] = $val['icon'];
                $msgList[$key]['msgType'] = $arrMsgExt && isset($arrMsgExt['msg_type']) ? $arrMsgExt['msg_type'] : 0;
                $quesContent = [];
                if ($val['icon'] == 2) {
                    $quesArr = $this->db->getRow("select uid,role from r_live_chatroom_message where id={$val['parent_id']}");
                    $quesRow = $this->db->getRow("select content,msg_type from r_live_chatroom_message_ext where mid={$val['parent_id']}");
                    $header2 = $nickname2 = '';
                    if(isset($quesArr['uid'])) {
                        $header2 = $this->redis->hget(REDIS_PREFIX . 'UserInfo_' . $quesArr['uid'],'header');
                        $nickname2 = $this->redis->hget(REDIS_PREFIX . 'UserInfo_' . $quesArr['uid'],'nickname');
                    }
                    $quesContent = array(
                        'userInfo' => array(
                            'uid'=>$quesArr && isset($quesArr['uid']) ? $quesArr['uid'] : 0,
                            'header'=>$header2 ? $header2 : "http://irun.hupu.com/static/bootstrap/img/jog_logo.png",
                            'nickname'=>$nickname2,
                            'role'=>$quesArr && isset($quesArr['role']) ? $quesArr['role'] : 0
                        ),
                        'content'=>$quesRow && isset($quesRow['content']) ? $quesRow['content'] : '',
                        'msgType'=>$quesRow && isset($quesRow['msg_type']) ? $quesRow['msg_type'] : 0
                    );
                    $quesContent['originSize'] = '0x0';//图片消息原图尺寸
                    if ($quesContent['msgType'] == 2 && $quesContent['content']) {
                        $originSize = getimagesize($quesContent['content']);
                        if ($originSize) {
                            $quesContent['originSize'] = $originSize[0].'x'.$originSize[1];//图片消息原图尺寸
                        }
                    }
                }
                $msgList[$key]['quesContent'] =$quesContent ? $quesContent : (object)$quesContent;
                $msgList[$key]['content'] =$arrMsgExt && isset($arrMsgExt['content']) ? $arrMsgExt['content'] : '';
                $msgList[$key]['originSize'] = '0x0';//图片消息原图尺寸
                if ($msgList[$key]['msgType'] == 2 && $msgList[$key]['content']) {//图片信息
                    $originSize = getimagesize($msgList[$key]['content']);
                    if ($originSize) {
                        $msgList[$key]['originSize'] = $originSize[0].'x'.$originSize[1];//图片消息原图尺寸
                    }
                }

                $msgList[$key]['light'] = $val['love_num'];
                $msgList[$key]['isReply'] = $val['is_reply'];
                $msgList[$key]['replyImId'] = $val['is_reply'] ? $this->getReplyImId($val['id']) : '';
                $msgList[$key]['addtime'] = $val['create_time'];
                $msgList[$key]['voiceSec'] = $arrMsgExt && isset($arrMsgExt['voice_sec']) ? $arrMsgExt['voice_sec'] : 0;;
                $msgList[$key]['voiceIsRead'] = $this->getVoiveMsgIsReadByUid($uid, $val['im_id']) ? 1 : 0;
                if ($sort == 1) {
                    $arrSort[] = $val['create_time'];
                }
                $isExistLight = $this->getUserIsLoveMsg($uid, $val['id']);
                $msgList[$key]['isLight'] = $isExistLight ? 1 : 0;//是否点赞
            }
        }
        $this->total = $this->db->getOne("select count(1) from r_live_chatroom_message where $where");
        if($sort == 1 && $arrSort) {//重新排序
            array_multisort($arrSort,SORT_ASC,$msgList);
        }
        return $msgList;
    }

    /**
     * 查询回复消息的imid
     */
    public function getReplyImId($mid) {
        $replyImId = $this->db->getOne("select im_id from r_live_chatroom_message where parent_id=$mid");
        return $replyImId ? $replyImId : '';
    }

    /**
     * 微课的待回复问题数
     */
    public function getNoRelyQuesNum($liveId) {
        return $this->db->getOne("select count(1) from r_live_chatroom_message where live_id=$liveId and icon=1 and is_reply=0");
    }

    /**
     * 查询用户是否可以提问
     */
    public function getUserCanQues($uid, $liveId, $goldNum) {
        //查询微课信息
        $arrInfo = $this->getLiveInfo($liveId, 'id,question_gold_num,status');
        if (!$arrInfo) {
            return -1;
        }

        if (in_array($arrInfo['status'], array(-5, 10))) {//已结束
            return -5;
        }

        //查询用户跟微课是否关联
        $isJoin = $this->getUserIsJoinLive($uid, $liveId);
        if (!$isJoin) {
            return -2;
        }
        //是否被禁言
        $isGag = $this->getUserIsGag($uid, $liveId);
        if ($isGag) {
            return -6;
        }
        if ($arrInfo['question_gold_num'] > 0) {
            //查询用户元宝
            $userGoldNum = $this->db->getOne("select gold_num from r_user_ext where uid=$uid");
            if ($userGoldNum < $arrInfo['question_gold_num']) {
                return -3;
            }
            if($goldNum < $arrInfo['question_gold_num']) {
                return -4;
            }

        }
        return 1;
    }

    /**
     * 收集所有用户发送消息内容接口
     * （[包含主播、主持、普通用户]+回复问题的消息处理）
     */
    public function addUserMsg(array $params) {
        $uid = (int)$params['uid'] ? (int)$params['uid'] : 0;
        $liveId = (int)$params['liveId'] ? (int)$params['liveId'] : 0;
        $type = (int)$params['type'] ? (int)$params['type'] : 0;// 0 普通消息 1 提问 2 回应消息
        $replyMid = (int)$params['replyMid'] ? (int)$params['replyMid'] : 0;//被回复的消息ID
        $msgType  = $params['msgType'] ? (int)$params['msgType'] : 0;//0 文字消息 1语音消息 2图片消息
        $imId = $params['imId'] ? $params['imId']  : '';//融云消息ID
        $content = $params['content'] ? $params['content']  : '';
        $goldNum = (int)$params['goldNum'] ? abs((int)$params['goldNum']) : 0;//提问需要扣除的元宝数
        $voiceSec = (int)$params['voiceSec'] ? (int)$params['voiceSec'] : 0;

        $info = $this->getLiveInfo($liveId,'id, speaker_id, host_id');
        //查询微课信息
        if ($type == 1) {
           $isCanQues = $this->getUserCanQues($uid, $liveId, $goldNum);
            if ($isCanQues <> 1) {
                return $isCanQues;
            }
            $r1 = $this->db->update("update r_user_ext set gold_num = gold_num-$goldNum where uid=$uid");
            if($r1) {
                $mid = $this->getIsExistMsg($imId);
                $this->addGoldCostLog($liveId, $uid, 1, 0, $goldNum, $mid, $goldNum*self::GOLD_RATE, 0, 0);
            }
            $result = $this->addMsg($uid, $imId, $liveId, 1, 0, $msgType, $content, $voiceSec);
            //"广播"到聊天室
//            $noReplyQuesNum = $this->getNoRelyQuesNum($liveId);
//            $extra = base64_encode(json_encode(array(
//                 'type'=>1,
//                  'msg_type'=>1,
//                  'ques_msg'=>array('quesNum'=>$noReplyQuesNum)
//            )));
//            $this->sendMsgToChatroom(array(
//                'target_id'=>$liveId,
//                'uid'=>$uid,
//                'content'=>$content,
//                'extra'=>$extra
//            ));
        } else if ($type == 2) {//回应消息
            $result = $this->addMsg($uid, $imId, $liveId, 2, $replyMid, $msgType, $content, $voiceSec);
        }else {
            $result = $this->addMsg($uid, $imId, $liveId, 0, 0, $msgType, $content, $voiceSec);
        }
        return $result;
    }

    /**
     * 新增消息
     */
    public function addMsg($uid, $imId, $liveId, $coin, $replyMid, $msgType, $content, $voiceSec) {
        $data = array(
            'im_id'=>$imId,
            'live_id'=>$liveId,
            'uid'=>$uid,
            'create_time'=>time()
        );

       switch($coin) {
           case 1:
               $data['parent_id'] = 0;
               $data['icon'] = 1;
               $data['role'] = 0;
               break;
           case 2:
               $info = $this->getLiveInfo($liveId,'id, speaker_id, host_id');
               if ($info['speaker_id'] == $uid)  {
                   $role = 1;
               }else {
                   $role = 2;
               }
               $data['parent_id'] = $replyMid;
               $data['icon'] = 2;
               $data['role'] = $role;
               break;
           case 0:
               $info = $this->getLiveInfo($liveId,'id, speaker_id, host_id');
               if ($info['speaker_id'] == $uid)  {
                   $role = 1;
               }elseif ($info['host_id'] == $uid) {
                   $role = 2;
               } else {
                   $role = 0;
               }
               $data['parent_id'] = $replyMid;
               $data['icon'] = 0;
               $data['role'] = $role;
               break;
           default:
            return false;
       }
        $insertId = $this->db->insertRow('r_live_chatroom_message',$data,mysqldb::INSERT_COMMON);
        if ($insertId) {
            $data = array(
                'live_id'=>$liveId,
                'mid'=>$insertId,
                'content'=>$content,
                'create_time'=>time(),
                'msg_type'=>$msgType,
                'voice_sec'=>$voiceSec
            );
            if ($msgType <> 1) {//语音消息太大，不另存
                $data['content_txt'] = $content;
            }
            $insertExtId = $this->db->insertRow('r_live_chatroom_message_ext',$data,mysqldb::INSERT_COMMON);
            if ($msgType == 1) {
                //新增用户阅读语音信息记录
                $this->addVoiceRead($uid, $imId);
            }

            if ($coin == 2) {//回复
                $this->db->update("update r_live_chatroom_message set is_reply=1 where id=$replyMid");
                $replyUid = $this->db->getOne("select uid from r_live_chatroom_message where id=$replyMid");
                if ($replyUid) {
                    //新增消息
                    $insertIdNew = $this->base->load('live/messageLive')->addLiveMsg(array(
                        'sourceId'=>$liveId,
                        'descType'=>'L2',
                        'toUid'=>$replyUid,
                        'mid'=>$insertId
                    ));
                    //发送消息
                    if ($insertIdNew) {
                        $a = $this->base->load('live/messageLive')->sendMsg(array(
                            'mid'=>$insertIdNew,
                            'sourceId'=>$liveId,
                            'descType'=>'L2',
                            'toUid'=>$replyUid,
                        ));
                    }
                }

            }
            //统计聊天室消息数量
            $msgNum = $this->sumLiveMsg($liveId);
            $this->db->update("update r_live_list set msg_num=$msgNum where id=$liveId");
        }
        return $insertId;
    }

    /**
     * 广播消息
     */
    public function sendMsgToChatroom($data) {
        $fromUserId = $data['uid'];
        $user = $data['user'];
        $toChatroomId = array($data['target_id']);
        $objectName = "RC:TxtMsg";
        $content = '{"content":"'.$data['content'].'","user":'.$user.',"extra":"'.$data['extra'].'"}';
        return $this->base->load('message')->messageChatroomPublish($fromUserId,$toChatroomId,$objectName,$content);
    }

    /**
     * 用户发布提问信息接口（元宝余额对应交互）
     */
    public function sendUserQues() {

    }

    /**
     *查询主播或主持结束微课接口（结束+微课信息汇总）
     */
    public function getAnalysisForOverLive($liveId) {
        $liveInfo = $this->getLiveInfo($liveId, 'id, title, image_url, join_num, start_time, end_time, speaker_id');
        if(!$liveInfo) {
            return array('detail'=>[], 'giftArr'=>[]);
        }
        $header = $this->redis->hget(REDIS_PREFIX . 'UserInfo_' . $liveInfo['speaker_id'],'header');
        $nickname = $this->redis->hget(REDIS_PREFIX . 'UserInfo_' . $liveInfo['speaker_id'],'nickname');
        //$costTime = $liveInfo['end_time'] - $liveInfo['start_time'] >0 ? $liveInfo['end_time'] - $liveInfo['start_time']: 0;
        $detail = array(
            'id'=>$liveInfo['id'],
            'title'=>$liveInfo['title'],
            'imageUrl'=>$liveInfo['image_url'],
            'userInfo'=>array(
                'uid'=>$liveInfo['speaker_id'],
                'nickname'=>$nickname,
                'header'=>$header ? $header : "http://irun.hupu.com/static/bootstrap/img/jog_logo.png"
            ),
            'startTime'=>$liveInfo['start_time'],
            'endTime'=>$liveInfo['end_time'],
            'joinNum'=>$liveInfo['join_num'],
            'quesNum'=>$this->sumQuesNum(0, $liveId, 0),
            'solveNum'=>$this->sumQuesNum(0, $liveId,1)
        );
        //礼物统计
        $giftArr = $this->getGiftAnalysis($liveId);
        sort($giftArr);
       return array('detail'=>$detail, 'giftArr'=>$giftArr);
    }

    /**
     * 结束微课
     */
    public function overLive($liveId, $uid) {
        $liveInfo = $this->getLiveInfo($liveId,'id,speaker_id,host_id');
        if (!$liveInfo) {
            return -1;
        }
        if(!in_array($uid, array($liveInfo['speaker_id'], $liveInfo['host_id']))) {
            return -2;//非法操作
        }
        $result =  $this->saveLiveStatus(2, $liveId);//结束
        if ($result) {
            //开始广播
            $extra = base64_encode(json_encode(array(
                'type'=>1,
                'msg_type'=>6//结束微课
            )));
            $header = $this->redis->hget(REDIS_PREFIX . 'UserInfo_' . $uid,'header');
            $nickname = $this->redis->hget(REDIS_PREFIX . 'UserInfo_' . $uid,'nickname');
            $result = $this->sendMsgToChatroom(array(
                'target_id'=>$liveId,
                'uid'=>$uid,
                'content'=>'',
                'extra'=>$extra,
                'user'=>json_encode(array('id'=>$uid,'name'=>$nickname, 'icon'=>$header ? $header : "http://irun.hupu.com/static/bootstrap/img/jog_logo.png"))
            ));
        }
            return $result;
    }

    /**
     * 查询指定微课所有用户提问及回答列表接口（排序规则：时间正序）
     */
    public function getQuesWallByLiveId() {

    }

    /**
     * 查询指定聊天室已被禁言的用户列表接口
     */
    public function getGagUserList($liveId, $id=0, $offset=20) {
        $where = "live_id=$liveId and last_time>".time();
        if ($id) {
           $where .=" and id > $id";
        }
        $result = $this->db->getAll("select uid from r_live_gag_user where $where limit $offset");
        $this->total = $this->db->getOne("select count(1) from r_live_gag_user where $where");
        return $result;
    }

    /**
     * 查询用户是否禁言
     */
    public function getUserIsGag($uid, $liveId) {
        $result = $this->db->getOne("select id from r_live_gag_user where  uid = $uid and live_id=$liveId and last_time>".time());
        return $result ? 1 : 0;
    }

    /**
     * 禁言指定聊天室的指定用户接口
     */
    public function addGagUser($liveId, $uid, $minute) {
         $result = $this->userGagAdd($liveId, $uid, $minute);
        if (!$result) {
            return false;
        }
        $data = array(
            'live_id'=>$liveId,
            'uid'=>$uid,
            'minute'=>$minute,
            'last_time'=>time()+$minute*60,
            'create_time'=>time()
        );
        $insertStr = common::arrayToString($data);
        return $this->db->insert("insert HIGH_PRIORITY into r_live_gag_user set {$insertStr} on duplicate key update {$insertStr}");
    }

    /**
     * 解禁指定聊天室的指定用户接口
     */
    public function rollbackGagUser($liveId, $uid) {
        $result = $this->userGagRollback($liveId, $uid);
        if (!$result) {
            return false;
        }
        return $this->db->delDataTable('r_live_gag_user',"live_id=$liveId and uid= $uid");
    }

    /**
     * 用户打赏礼物接口（+广播）
     */
    public function sendGift($uid, $liveId, $giftId) {
        //用户是否加入
        $isJoin = $this->getUserIsJoinLive($uid, $liveId);
        if (!$isJoin) {
            return -1;
        }
        //用户余额是否充足
        $giftArr = common::$giftList;
        if(!isset($giftArr[$giftId])) {
           return -2;
        }
        $goldNum = $giftArr[$giftId]['goldNum'];
        if ($goldNum > 0) {
            //查询用户元宝
            $userGoldNum = $this->db->getOne("select gold_num from r_user_ext where uid=$uid");
            if ($userGoldNum < $goldNum) {
                return -3;//元宝数量不足
            }
            //扣除余额
            $this->db->update("update r_user_ext set gold_num = gold_num-$goldNum where uid=$uid");
        }

        //记录流水
        $this->addGoldCostLog($liveId, $uid, 2, $giftId, $goldNum, 0, (float)$giftArr[$giftId]['price'], 0);
        //广播消息
        $extra = base64_encode(json_encode(array(
            'type'=>1,
            'msg_type'=>3,//礼物
            'gift_msg'=>array('id'=>$giftId)
        )));
        $header = $this->redis->hget(REDIS_PREFIX . 'UserInfo_' . $uid,'header');
        $nickname = $this->redis->hget(REDIS_PREFIX . 'UserInfo_' . $uid,'nickname');
        $result = $this->sendMsgToChatroom(array(
            'target_id'=>$liveId,
            'uid'=>$uid,
            'content'=>'',
            'extra'=>$extra,
            'user'=>json_encode(array('id'=>$uid,'name'=>$nickname, 'icon'=>$header ? $header : "http://irun.hupu.com/static/bootstrap/img/jog_logo.png"))
        ));
        return 1;
    }

    /**
     * 用户喜欢问题接口（+广播）
     */
    public function addLight($uid, $liveId, $imId){
        //用户是否加入
        $isJoin = $this->getUserIsJoinLive($uid, $liveId);
        if (!$isJoin) {
            return -1;
        }
        $arrMsg = $this->db->getRow("select id from r_live_chatroom_message where im_id='$imId' and live_id=$liveId");
        if (!$arrMsg) {
            return -2;//这个消息不存在 或者 消息跟聊天室不匹配
        }
        $isExistLight = $this->getUserIsLoveMsg($uid, $arrMsg['id']);
        if ($isExistLight) {
            return -3;//已经点赞过
        }
        $data = array(
            'live_id'=>$liveId,
            'mid'=>$arrMsg['id'],
            'im_id'=>$imId,
            'uid'=>$uid,
            'create_time'=>time()
        );
        //记录点赞
        $insertStr = common::arrayToString($data);
        $this->db->insert("insert HIGH_PRIORITY into r_live_lights set {$insertStr} on duplicate key update {$insertStr}");
        //更新消息点赞数
        $num = $this->sumMsgLight($arrMsg['id']);
        $this->updateMsgLight($arrMsg['id'], $num);
        //广播到聊天室
            $extra = base64_encode(json_encode(array(
                  'type'=>1,
                  'msg_type'=>4,
                  'light_msg'=>array('light'=>$num, 'imId'=>$imId)
            )));
        $header = $this->redis->hget(REDIS_PREFIX . 'UserInfo_' . $uid,'header');
        $nickname = $this->redis->hget(REDIS_PREFIX . 'UserInfo_' . $uid,'nickname');
            $result = $this->sendMsgToChatroom(array(
                'target_id'=>$liveId,
                'uid'=>$uid,
                'content'=>'',
                'extra'=>$extra,
                'user'=>json_encode(array('id'=>$uid,'name'=>$nickname, 'icon'=>$header ? $header : "http://irun.hupu.com/static/bootstrap/img/jog_logo.png"))
            ));
//        return $result;
       return 1;
    }

    /**
     * 查询用户是否点赞过消息
     */
    public function getUserIsLoveMsg($uid, $mid) {
        return $isExistLight = $this->db->getOne("select id from r_live_lights where uid=$uid and mid=$mid");
    }

    /**
     * 查询用户是否播放过语音消息
     */
    public function getVoiveMsgIsReadByUid($uid, $imId) {
        return $this->db->getOne("select id from r_live_voice_read where uid=$uid and im_id='$imId'");
    }

    /**
     * 统计消息点赞数
     */
    public function sumMsgLight($mid) {
        return $this->db->getOne("select count(1) from r_live_lights where mid=$mid");
    }

    /**
     * 统计加入的聊天室人数
     */
    public function sumJoinNum($liveId) {
        return $this->db->getOne("select count(1) from r_live_user where live_id=$liveId");
    }

    /**
     * 统计提问元宝数
     */
    public function sumQuesGoldNum($uid, $liveId) {
        $where = "live_id=$liveId  and type=1 and balance_type=0";
        if ($uid) {
            $where .= " and uid=$uid";
        }
       return  $this->db->getOne("select sum(`gold_num`) as goldNum from r_live_gold_list where $where");
    }

    /**
     * 统计打赏礼物元宝数
     */
    public function sumGiftNum($uid, $liveId) {
        return  $this->db->getOne("select sum(`gold_num`) as goldNum from r_live_gold_list where live_id=$liveId and uid=$uid and type=2 and balance_type=0");
    }

    /**
     * 统计提问数
     * @param $uid
     * @param $liveId
     * @param $type  1 : 已回复 2 未回复  0 :全部
     * @return mixed
     */
    public function sumQuesNum($uid, $liveId, $type=0) {
        $where = "live_id=$liveId  and icon=1 and status=0";
        if ($uid) {
            $where .=" and uid=$uid";
        }
        if ($type == 1) {
            $where .= " and is_reply=1";
        } else if($type == 2) {
            $where .= " and is_reply=0";
        }
        return  $this->db->getOne("select count(1) from r_live_chatroom_message where $where");
    }

    /**
     * 统计微课消息数
     */
    public function sumLiveMsg($liveId) {
        return  $this->db->getOne("select count(1) from r_live_chatroom_message where live_id=$liveId");
    }

    /**
     * 更新消息点赞数
     */
    public function updateMsgLight($mid, $num) {
        $this->db->update("update r_live_chatroom_message set love_num=$num where id=$mid");
    }

    /**
     * 新增OR更新 语音消息阅读
     */
    public function addVoiceRead($uid, $imId) {
        $data = array(
            'uid' => $uid,
            'im_id'=> $imId
        );
        $insertStr = common::arrayToString($data);
        return $this->db->insert("insert HIGH_PRIORITY into r_live_voice_read set {$insertStr} on duplicate key update {$insertStr}");
    }

    /**
     * 查询指定微课的用户打赏排行榜接口
     */
    public function getRankListByLiveId(array $params) {
        $liveId = $params['liveId'];
        $start     = $params['start'] ? (int)$params['start'] : 0;
        $offset = (int)$params['offset'] ? (int)$params['offset'] : 20;

        $where = "live_id=$liveId and `type`=2 and balance_type=0";
        $list = $this->db->getAll("select *,sum(`gold_num`) as totalGoldNum from r_live_gold_list where  $where group by uid order by totalGoldNum desc limit $start,$offset");
        $this->total = $this->db->getOne("select count(1) from (select count(1) from r_live_gold_list where  $where group by uid) as temp");
        return $list;
    }

    /**
     * 用户加入聊天室
     */
    public function addUserToChatroom($uid, $liveId) {
        //查询是否加入
        $isJoin = $this->getUserIsJoinLive($uid, $liveId);
        if ($isJoin) {
            return 1;//已经加入
        }
        //微课信息
        $liveInfo = $this->getLiveInfo($liveId);
        if (!$liveInfo) {
            return -1;//聊天室不存在
        }
        if(in_array($liveInfo['status'], array(liveModel::CANCEL_STATUS, liveModel::OVER_STATUS))) {
            return -3;//已取消或结束
        }
        if($liveInfo['limit_num']>0 && ($liveInfo['join_num'] >= $liveInfo['limit_num'])) {
            return -4;//人数已满
        }
        //是否收费
        $price = $liveInfo['price'];
        if ($price > 0) {
            $isPay = $this->getUserIsSignUpLive($uid, $liveId);//用户是否付费
            if (!$isPay) {
                return -2;//未付费
            }
        }
        $insertId = $this->chatUserAdd($uid, $liveId);
        if ($insertId) {
            $joinNum = $this->sumJoinNum($liveId);
            $this->db->update("update r_live_list set join_num=$joinNum where id=$liveId");
            //开始广播
            $extra = base64_encode(json_encode(array(
                'type'=>1,
                'msg_type'=>5,//加入微课
                'live_msg'=>array('join_num'=>$joinNum)
            )));
            $header = $this->redis->hget(REDIS_PREFIX . 'UserInfo_' . $uid,'header');
            $nickname = $this->redis->hget(REDIS_PREFIX . 'UserInfo_' . $uid,'nickname');
            $result = $this->sendMsgToChatroom(array(
                'target_id'=>$liveId,
                'uid'=>$uid,
                'content'=>'',
                'extra'=>$extra,
                'user'=>json_encode(array('id'=>$uid,'name'=>$nickname, 'icon'=>$header ? $header : "http://irun.hupu.com/static/bootstrap/img/jog_logo.png"))
            ));
        }
        return 1;
    }

    /**
     * 增加聊天室用户
     */

    public function chatUserAdd($uid, $liveId) {
        $role = $this->getUserRole($uid, $liveId);
        $data['live_id'] = $liveId;
        $data['uid'] = $uid;
        $data['status'] = 0;
        $data['create_time'] = time();
        $data['role'] = $role;
        return $result = $this->db->insertRow('r_live_user',$data,mysqldb::INSERT_COMMON);
    }

    /**
     * 查询用户角色
     */
    public function getUserRole($uid, $liveId) {
        $role = 0;
        $liveInfo = $this->getLiveInfo($liveId);
        if($liveInfo){
            if($liveInfo['speaker_id'] ==  $uid) {
                $role = 1;
            } elseif($liveInfo['host_id'] ==  $uid) {
                $role = 2;
            }
        }
        return $role;
    }

    /**
     * @param $liveId
     * @param $uid
     * @param $type   '类型： 1:提问 2：礼物 3 :充值',
     * @param $giftType '礼物类型：1：游艇 2皮鞭 3 润喉糖 4花束',
     * @param $goldNum
     * @param $mid  '产生元宝的主体ID（eg：提问消息的ID）'
     * @param $goldPrice
     * @param $balanceType '收支类型： 0 支出 1 收入',
     */
    public function addGoldCostLog($liveId, $uid, $type, $giftType=0, $goldNum, $mid, $goldPrice, $balanceType, $giveGoldNum = 0) {
        $data['live_id'] = $liveId;
        $data['uid'] = $uid;
        $data['type'] = $type;
        $data['gift_type'] = $giftType;
        $data['gold_num'] = $goldNum;
        $data['mid'] = $mid;
        $data['gold_price'] = $goldPrice;
        $data['balance_type'] = $balanceType;
        $data['create_time'] = time();
        if($type == 3) {
            $data['give_gold_num'] = $giveGoldNum;
        }
        $result = $this->db->insertRow('r_live_gold_list',$data,mysqldb::INSERT_COMMON);
        if ($result) {
            if ($type == 3) {
                $orderId = $mid;
                $orderInfo = $this->load('order')->getOrderByOrderId($orderId);
                if($orderInfo && ($orderInfo['add_gold_status'] ==0)) {
                    $re = $this->db->update("update r_user_ext set gold_num=gold_num+$goldNum where uid=$uid");
                    if ($re) {
                        $this->load('order')->setAddGoldStatus($orderId);
                    }
                }
            } else {
                //个人元宝汇总
                $data = [];
                $data['live_id'] = $liveId;
                $data['uid'] = $uid;
                $data['ques_gold_num'] = $this->sumQuesGoldNum($uid, $liveId);
                $data['gift_gold_num'] = $this->sumGiftNum($uid, $liveId);
                $insertStr = common::arrayToString($data);
                $result2 = $this->db->insert("insert HIGH_PRIORITY into r_live_gold_sum set {$insertStr} on duplicate key update {$insertStr}");
            }
        }
        return $result;
    }

    /**
     * 查询用户元宝充值消费记录接口（我的账单）
     */
    public function getUserGoldCostList(array $params) {
        $uid = $params['uid'];
        $id = $params['id'];
        $offset = (int)$params['offset'] ? (int)$params['offset'] : 20;
        $where = "uid=$uid";
        if ($id) {
            $where .=" and id <$id";
        }
        $sql = "select count(1) from r_live_gold_list where $where";
        $this->total = $this->db->getOne("$sql");
        if (!$this->total) {
            return [];
        }
        $sql2 = "select * from r_live_gold_list where $where order by id desc limit $offset";
        $list = $this->db->getAll("$sql2");
        return $list;

    }
    /********************************************接口END*****************************************/

    /*******************************************定时器******************************************/
    /**
     * cron 微课未开始 变为进行中
     * +发消息通知
     */
    public function autoUpShelf() {
        $now = time();
        //查询全部未开始微课
        $list =  $this->db->getAll("select id,end_time from r_live_list where status = 0 and $now >= start_time");
        if (!$list) {
            echo '--1--'.date('Y-m-d H:i:s').' 全部未开始微课列表为空'.PHP_EOL;
            return false;
        }
        foreach ($list as $key=>$val) {
            $r = $this->saveLiveStatus(3, $val['id']);//进行中
            if ($r) {
                echo '--1--'.date('Y-m-d H:i:s').'id：'.$val['id'].'---'.' 成功变更为-进行中'.PHP_EOL;
                //查询加入微课的用户
                $arrUid = $this->db->getAll("select uid from r_live_user where live_id={$val['id']}");
                if ($arrUid) {
                    foreach ($arrUid as $k2=>$v2) {
                        //新增消息
                        $insertId = $this->base->load('live/messageLive')->addLiveMsg(array(
                            'sourceId'=>$val['id'],
                            'descType'=>'L1',
                            'toUid'=>$v2['uid'],
                            'mid'=>0
                        ));
                        //发送消息
                        if ($insertId) {
                            $a = $this->base->load('live/messageLive')->sendMsg(array(
                                'mid'=>$insertId,
                                'sourceId'=>$val['id'],
                                'descType'=>'L1',
                                'toUid'=>$v2['uid'],
                            ));
                        }
                    }

                }

            } else {
                echo '--1--'.date('Y-m-d H:i:s').'id：'.$val['id'].'---'.' 失败变更为-进行中'.PHP_EOL;
            }
        }
    }

    /**
     * 更新微课状态
     * @param $type 1 取消微课 2 结束微课 3 开始微课
     * @param $liveId
     * @return int
     */
    public function saveLiveStatus($type, $liveId) {
        if ($type == 1) {
            $sql = "update r_live_list set status = -5 where id=$liveId and status = 0";
        } else if($type == 2) {
            $time = time();
            $sql = "update r_live_list set status = 10,end_time=$time where id=$liveId and status = 5";
        } else if($type == 3) {
            $time = time();
            $sql = "update r_live_list set status = 5 where id=$liveId and status = 0";
        } else {
            return 0;
        }
        return $this->db->update($sql);
    }


}